package com.xbongbong.pro.statistic.help.strategy.field.method;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.SizeConstant;
import com.xbongbong.paas.elasticsearch.pojo.StatisticBiFormDataEntity;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.ReflectHelper;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.paas.elasticsearch.pojo.ChartFieldsAnalysisEntityExt;
import com.xbongbong.pro.statistic.help.CustomHelp;
import com.xbongbong.pro.statistic.help.strategy.field.FieldAnalysisStrategy;
import com.xbongbong.pro.statistic.pojo.FieldAnalysisPojo;
import com.xbongbong.pro.statistic.result.pojo.FieldAttrPojo;
import com.xbongbong.saas.constant.StringConstant;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 字段type为LINK_BUSINESS时的字段解析
 * @author zhouwq
 * @date 2020/9/8 9:58
 */

@Component
public class LinkBusinessFieldAnalysis implements FieldAnalysisStrategy {

    @Resource
    private CustomHelp customHelp;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;

    @Override
    public Map<String, String> doAnalysisField(FieldAnalysisPojo fieldAnalysisPojo) throws XbbException{
        Map<String, String> results = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (!fieldAnalysisPojo.getIsChart()) {
            return results;
        }
        FieldAttrPojo field = fieldAnalysisPojo.getField();
        ChartEntity chartEntity = fieldAnalysisPojo.getChartEntity();
        String linkText = field.getLinkedText();
        List<String> values = fieldAnalysisPojo.getValuesResult();
        if (linkText != null) {
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            SearchRequest searchRequest = new SearchRequest();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolean isSingle = EsUtil.getSingle(chartEntity);
            Boolean isWarningSync = fieldAnalysisPojo.getIsWarningSync();
            customHelp.chartDataEsQuery(chartEntity, sourceBuilder, boolQueryBuilder, searchRequest, fieldAnalysisPojo, isWarningSync);
            //判断单表且在data中
            boolean isInDataAndSingle = EsUtil.setInData(field.getFieldType()) && isSingle;
            String attr = isInDataAndSingle ? "data." + field.getAttr() : field.getAttr();
            String linkTextAttr = isInDataAndSingle ? "data." + linkText : linkText;
            sourceBuilder.fetchSource(new String[]{linkTextAttr, attr}, null);

            attr = EsUtil.addKeyWord(field.getFieldType(), attr);
            List<String> valuesList = new ArrayList<>();
            for (String value : values) {
                //处理value有多个值的情况 例如:value = "1,2,3";
                if (value.contains(StringConstant.COMMA)) {
                    String[] arr = value.split(StringConstant.COMMA);
                    valuesList.addAll(Arrays.asList(arr));
                } else {
                    valuesList.add(value);
                }
            }
            boolQueryBuilder.filter(termsQuery(attr, valuesList));

            PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, SizeConstant.PAGE_SIZE);
            searchRequest.source(sourceBuilder);
            //单表多表判断
            if (isSingle) {
                XbbAggregatedPage<ChartFieldsAnalysisEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, ChartFieldsAnalysisEntityExt.class);
                List<ChartFieldsAnalysisEntityExt> esList = esEntities.getContent();
                for (ChartFieldsAnalysisEntityExt esEntity : esList) {
                    if(field.getAttr() == null){
                        continue;
                    }
                    results.put(esEntity.getData().getString(field.getAttr()), esEntity.getData().getString(linkText));
                }
            } else {
                XbbAggregatedPage<StatisticBiFormDataEntity> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, StatisticBiFormDataEntity.class);
                List<StatisticBiFormDataEntity> esList = esEntities.getContent();
                if (esList.size() > 0) {
                    for (StatisticBiFormDataEntity esEntity : esList) {
                        if(field.getAttr() == null){
                            continue;
                        }
                        Object o = ReflectHelper.valueGet(esEntity, linkText);
                        if(o == null){
                            o= "";
                        }
                        results.put(ReflectHelper.valueGet(esEntity, field.getAttr()).toString(), o.toString());
                    }
                }
            }
        }

        return results;
    }
}
